import hashlib
import time
import os

import requests

import sys
sys.path.append('..')
from douyin.haiwangou.dou_yin import *
from aikucun.haiwangou.akc_bill import *
from pinduoduo.haiwangou.pdd_bill import *
from xiaohongshu.haiwangou.xhs import *
from kuaishou.haiwangou.ks import *
from jingdong.haiwangou.jd import *


def get_account_list(mobile):
    try:
        secret = "P4I8HCOP1OP7432XZVKR2MPJKKVQ7J"
        post_url = host + 'api/v1/storeAccount/getAccountListByHWG/'+mobile
        timestamp = int(time.time() * 1000)
        text = "haiwangou-key{}{}".format(timestamp, secret)
        sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
        logger.info(post_url + "?appId=haiwangou-key&sign={}&timestamp={}".format(sign.upper(), timestamp))
        response = requests.get(post_url + "?appId=haiwangou-key&sign={}&timestamp={}".format(sign.upper(), timestamp))
        if response.status_code == 200:
            accounts = response.json()
            logger.info(accounts['data'])
            return accounts['data']
        else:
            logger.info("获取账号密码信息失败")
    except:
        traceback.print_exc()
    return []

# 按照storeKey分组
def group_by_store_key(account_list):
    group_store = {}
    for store in account_list:
        if store['storeKey'] != 'redBook':
            if store['storeKey'] in group_store.keys():
                item = list(group_store[store['storeKey']])
                item.append(store)
                group_store[store['storeKey']] = item
            else:
                item = [store]
                group_store[store['storeKey']] = item
    rd_filter = list(filter(lambda x: x['storeKey'] == 'redBook', account_list))
    if len(rd_filter) > 0:
        group_store['redBook'] = rd_filter
    return group_store

def change_gate(mobile):
    requests.get(f'http://1.95.166.150:8997/api/v1/device/changeGate/{mobile}')

if __name__ == '__main__':
    log_file = os.path.join(os.getcwd(), 'logs', f'{datetime.datetime.now().strftime("%Y-%m-%d")}-server6.txt')
    if not os.path.exists(log_file):
        logger.add(log_file)
    # host = 'http://1.95.166.150:8997/'
    host = "http://172.16.28.199:8989/"
    mobile_list = ['17399882026']
    for mobile in mobile_list:
        account_list = get_account_list(mobile)
        if len(account_list) == 0:
            logger.info('没有店铺账号信息')
        else:
            logger.info(f'切换卡槽为【{mobile}】')
            # change_gate(mobile)
            # time.sleep(30)
            group_account = group_by_store_key(account_list)
            for store_key in group_account:
                if 'DY' == store_key:
                    dy_main(host, group_account[store_key])
                elif 'ikc' == store_key:
                    akc_main(host, group_account[store_key])
                elif 'pdd' == store_key:
                    pdd_main(host, group_account[store_key])
                elif 'redBook' == store_key:
                    xhs_main(host, group_account[store_key])
                elif 'ks' == store_key:
                    ks_main(host, group_account[store_key])
                elif 'JD' == store_key:
                    jd_main(host, group_account[store_key])

